package cn.edu.gcu.lost.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.gcu.lost.util.UploadFile;

@Controller
@RequestMapping(value = "/file")
public class FileController {

    @ResponseBody
    @RequestMapping(value = "/uploadImgs")
    public Map<String, Object> uploadImgs(@RequestParam("files") MultipartFile[] files, HttpServletRequest request,
                                          HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<String, Object>(16);
        Pattern pattern = Pattern.compile(".+(.JPEG|.jpeg|.JPG|.jpg|.GIF|.gif|.BMP|.bmp|.PNG|.png)$");
        String fileName = null;
        System.out.println(fileName);
        for (MultipartFile file : files) {
            fileName = file.getOriginalFilename();
            if (!pattern.matcher(fileName.toLowerCase()).find()) {
                resultMap.put("result", "faild");
                resultMap.put("cause", "exist file pattern error");
                return resultMap;
            }
        }
        String basePath = request.getSession().getServletContext().getRealPath("/");
        StringBuffer strBuffer = new StringBuffer();
        try {
            for (MultipartFile file : files) {
                strBuffer.append(UploadFile.updatePic(basePath, file));
                strBuffer.append(";");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", "faild");
            resultMap.put("cause", "upload process has error");
            return resultMap;
        }
        Map<String, Object> dataMap = new HashMap<String, Object>(16);
        dataMap.put("urls", strBuffer.toString());
        resultMap.put("result", "success");
        resultMap.put("data", dataMap);
        return resultMap;
    }
}
